package cc.gu.tank.sprite;

import cc.gu.tank.enums.Direction;
import cc.gu.tank.enums.Group;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.Image;
import javafx.scene.input.KeyCode;

import java.util.List;

/**
 * @Author: GuSongLiao
 * @Date: 2025/9/29 10:41
 * @Description: 角色类，可移动物体
 */
public class Role extends Sprite implements MoveAble{

    double oldX, oldY;

    protected double speed = 5;

    protected Direction direction;

    //默认自己的一方
    protected Group group = Group.OWNSIDE;

    /**
     * 是否存活
     */
    protected boolean live = true;

    /**
     * 是否可移动,按下方向键可移动
     */
    protected boolean moveAble = false;


    public Role(Image image, double x, double y, double width, double height) {
        super(null, x, y, width, height);
        this.oldX = x;
        this.oldY = y;
        this.image = image;
    }

    @Override
    public void move() {
        oldX = x;
        oldY = y;
        if (live && moveAble) {
            switch (direction) {
                case UP:
                    y = y - speed;
                    break;
                case DOWN:
                    y = y + speed;
                    break;
                case LEFT:
                    x = x - speed;
                    break;
                case RIGHT:
                    x = x + speed;
                    break;
            }
        }
    }

    @Override
    public void stop() {
        moveAble = false;
    }

    @Override
    public void draw(GraphicsContext graphicsContext2D) {
        move();
        super.draw(graphicsContext2D);
    }

    /**
     * 按下按键
     */
    public void pressed(KeyCode keyCode) {
        if (this.group == Group.ENEMY) return;
        switch (keyCode) {
            case UP:
                direction = Direction.UP;
                moveAble = true;
                break;
            case DOWN:
                direction = Direction.DOWN;         moveAble = true;
                break;
            case LEFT:
                direction = Direction.LEFT;         moveAble = true;
                break;
            case RIGHT:
                direction = Direction.RIGHT;         moveAble = true;
                break;
        }
    }

    public void released(KeyCode keyCode) {
        if (this.group == Group.ENEMY) return;
        switch (keyCode) {
            case UP:
            case DOWN:
            case LEFT:
            case RIGHT:
                stop();
                break;
        }
    }

    /**
     * 碰撞检测
     */
    public boolean impactCheck(Sprite sprite) {
        if (sprite != null && !sprite.equals(this) && getController().intersects(sprite.getController())) {
            return true;
        }
        return false;
    }

    /**
     * 碰撞逻辑
     */
    public Sprite impact(List<? extends Sprite> sprites) {
        for (Sprite sprite : sprites) {
            if (impactCheck(sprite)) {
                return sprite;
            }
        }
        return null;
    }
}
